package cn.sourcespro.shiro.security;

import cn.sourcespro.shiro.util.JwtTokenUtil;
import cn.sourcespro.shiro.util.RespUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/23
 */
public class JwtFilter extends AccessControlFilter {

    private static final Logger log = LoggerFactory.getLogger(AccessControlFilter.class);

    public static final String DEFAULT_JWT_PARAM = "jwt";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (null != getSubject(request, response)
                && getSubject(request, response).isAuthenticated()) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest servletRequest = WebUtils.toHttp(request);
        String token = servletRequest.getHeader("token");
        if(StringUtils.isNotBlank(token)){
            try {
                DecodedJWT verifyToken = JwtTokenUtil.verifyToken(token);
                if (CollectionUtils.isNotEmpty(verifyToken.getAudience())) {
                    return true;
                }
                return false;
            } catch (AuthenticationException e) {
                log.error(e.getMessage(),e);
                RespUtil.send(response, "token无效", HttpStatus.FORBIDDEN);
            }
        }
        return false;
    }

}
